import React, { useEffect, useState } from 'react';
import { Drawer, Form, Input, Tree, Button, Space, message, Spin } from 'antd';
import { Role } from '@/pages/Settings/RoleManagement/types';
import { rolesApi } from '@/api/roles';
import { useMenuManagement } from '../hooks';

const { TextArea } = Input;

interface RoleDrawerProps {
  visible: boolean;
  editingRole: Role | null;
  form: any;
  onClose: () => void;
  onFinish: (values: any) => void;
}

const RoleDrawer: React.FC<RoleDrawerProps> = ({ visible, editingRole, form, onClose, onFinish }) => {
  const { menus, loading: menuLoading } = useMenuManagement();
  const [checkedKeys, setCheckedKeys] = useState<number[]>([]);
  const [treeLoading, setTreeLoading] = useState(false);
  const [roleLoading, setRoleLoading] = useState(false);

  // 编辑时回显角色详情
  useEffect(() => {
    if (visible && editingRole) {
      setRoleLoading(true);
      rolesApi.getRole(editingRole.id).then(res => {
        form.setFieldsValue(res);
      }).finally(() => setRoleLoading(false));
    } else if (visible) {
      form.resetFields();
    }
  }, [visible, editingRole, form]);

  // 获取角色已分配菜单/按钮ID，menus 加载后再设置 checkedKeys
  useEffect(() => {
    if (visible && editingRole && menus.length > 0) {
      setTreeLoading(true);
      rolesApi.getMenus(editingRole.id).then(res => {
        const checked = res || [];
        setCheckedKeys(checked);
        // debug 输出
        const collectKeys = (arr: any[]): number[] => arr.flatMap((item: any) => [item.id, ...(item.children ? collectKeys(item.children) : [])]);
        const allMenuKeys = collectKeys(menus);
        const notFound = checked.filter((k: number) => !allMenuKeys.includes(k));
        if (notFound.length > 0) {
          console.warn('【DEBUG】后端返回的 checkedKeys 中，以下 key 在菜单树中找不到：', notFound);
        }
      }).finally(() => setTreeLoading(false));
    } else if (visible) {
      setCheckedKeys([]);
    }
  }, [visible, editingRole, menus]);

  // 提交时分配菜单/按钮权限
  const handleFinish = async (values: any) => {
    if (editingRole) {
      await onFinish(values); // 先更新角色基本信息
      setTreeLoading(true);
      try {
        await rolesApi.setMenus(editingRole.id, checkedKeys);
        message.success('权限分配成功');
        onClose();
      } catch {
        message.error('权限分配失败');
      } finally {
        setTreeLoading(false);
      }
    } else {
      await onFinish(values); // 新建角色后，建议在主表刷新后再分配权限
    }
  };

  // 菜单树数据适配
  const treeData = menus.map(item => ({
    key: item.id,
    title: item.name,
    children: item.children ? item.children.map(child => ({
      key: child.id,
      title: child.name,
      children: child.children ? child.children.map(btn => ({
        key: btn.id,
        title: btn.name,
      })) : undefined,
    })) : undefined,
  }));

  return (
    <Drawer
      title={editingRole ? '编辑角色' : '新增角色'}
      open={visible}
      onClose={onClose}
      width={600}
      destroyOnClose
      maskClosable
      forceRender
    >
      <Spin spinning={roleLoading}>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleFinish}
        >
          <Form.Item
            name="name"
            label="角色名称"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input placeholder="请输入角色名称" />
          </Form.Item>

          <Form.Item
            name="code"
            label="角色编码"
            rules={[{ required: true, message: '请输入角色编码' }]}
          >
            <Input placeholder="请输入角色编码" />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
          >
            <TextArea rows={3} placeholder="请输入角色描述" />
          </Form.Item>

          {editingRole && (
            <Form.Item label="菜单/按钮权限">
              <Spin spinning={treeLoading || menuLoading}>
                <Tree
                  checkable
                  treeData={treeData}
                  checkedKeys={checkedKeys}
                  onCheck={keys => setCheckedKeys(Array.isArray(keys) ? keys as number[] : [])}
                  defaultExpandAll
                />
              </Spin>
            </Form.Item>
          )}

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={treeLoading}>
                {editingRole ? '更新' : '创建'}
              </Button>
              <Button onClick={onClose} disabled={treeLoading}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Spin>
    </Drawer>
  );
};

export default RoleDrawer; 